<?php

/**
 * The planets class holds all of the functions related to planets
 * IE: Creating/Editing them, displaying them.
 *
 * @author Charles
 */
class planets {
    
    /**
     * Creates a planet,.
     * 
     * @author Charles Nicholson
     * 
     * @global object $mysqli
     * @param mixed $name
     * @param int $size
     * 
     * @return void Function returns nothing, redirects user.
     */
    function createPlanet($name, $size) {
        // Need db variable
        global $mysqli;

        // Make sure $name isnt empty
        if(empty($name) || $name == NULL) {
            die("Error: Name must be filled out");
        }
        
        
        // Sanitize input for insertion.
        $name = $mysqli->real_escape_string($name);
        
        
        
        // Check to see if size is integer
        if(!is_numeric($size)) {
            // if it isn't cancel function
            // in realtime enviroment I'd pass to an error class
            // instead of exiting so ungracefully
            die("Size must be numeric.");
        }
        
        // Check to see if size is within range
        if($size < 1 || $size > 30) {
            die("Size must be between 1 and 30.");
        }
        
        // See if planet name is in use
        $query = "SELECT name FROM planets WHERE name = '$name'";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        $num_rows = $result->num_rows;
        
        if($num_rows > 0) {
            echo 'Error: Name in use. <a href="createPlanet.php">Try again.</a>';
            exit();
        }
        
        // Setup query
        $query = "INSERT INTO planets VALUES ('', '$name', '$size')";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        // Close link
        mysqli_close($mysqli);
        
        header("Location: listPlanets.php");
    }
    
    /**
     * Lists planets in a nice div.
     * 
     * @author Charles Nicholson
     * 
     * @global object $mysqli
     * 
     * @return void Echo's HTML.
     */
    function listPlanets() {
        global $mysqli;
        global $deposits;
        
        // Setup query to grab planets
        $query = "SELECT * FROM planets ORDER BY name";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        // Loop through dataset and store in array which we print
        while ($planet = $result->fetch_array(MYSQLI_ASSOC)) {
            // Get deposit amount 
            $count = $deposits->countDeposits($planet['id']);
            
            // Print table with information
            $HTML = "\n<br />\n
                     <br />
                     <div class='name'>%s</div>\n
                     <div class='size'>%u</div>\n
                     <div class='deposits'>%u</div>\n
                     <div class='edit_delete'>\n
                        \t<a href='editPlanet.php?id=%u' class='editLink'>Edit</a>\n
                        \t<a  href='deletePlanet.php?id=%u' onclick='return confirm_alert(this); return false;' class='deleteLink'>Delete</a>\n
                     </div>";
            printf($HTML, $planet['name'], $planet['size'], $count, $planet['id'], $planet['id']);
        }
        
    }
    
    /**
     * 
     * Description: Returns how many deposits per planet
     * 
     * @global object $mysqli
     * @param int $planetID
     * @return int
     */
    function countDeposits($planetID) {
        global $mysqli;
        
        // Setup query to grab deposits
        $query = "SELECT COUNT(*) FROM deposits WHERE planet_id = $planetID";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        $count = $result->num_rows;
        $count = $count[0];
        
        return $count;
    }
    
    /**
     * Description: Searches and returns planet info, by name or ID.
     * 
     * @global object $mysqli
     * @param int $planetID
     * @param string $name
     * @return array
     */
    function planetInfo($planetID, $name=NULL) {
        global $mysqli;
        
        if($planetID != NULL) {
            // Setup query to get info
            $query = "SELECT * FROM planets WHERE id = '$planetID'";
            $result = $mysqli->query($query) or die(mysqli_error($mysqli));

            $info = $result->fetch_array(MYSQLI_ASSOC);

            return $info;
        } else {
            // Setup query to get info
            $query = "SELECT * FROM planets WHERE name = '$name'";
            $result = $mysqli->query($query) or die(mysqli_error($mysqli));

            $info = $result->fetch_array(MYSQLI_ASSOC);

            return $info;
        }
    }
    
    /**
     * 
     * @global object $mysqli
     * @global object $terrain
     * @param int $planetID
     * @param string $name
     * @param int $size
     * @param string $coordiantes
     * @param int $type
     * 
     * @return void Updates database,
     */
    function editPlanet($planetID, $name, $size, $coordinates, $type) {
        global $mysqli;
        global $terrain;
        
        // do some error checking
        if(!isset($planetID) || empty($planetID)) {
            echo 'Error: ID cannot be empty. Please try again';
            exit();
        }
        
        // Check to see if planetID is an integer, if not try to cast it as one
        // and check again
        
        if(!is_numeric($planetID)) {
            $planetID = (int) $planetID;
            
            if(!is_numeric($planetID)) {
                echo 'Error: ID must be a number. Please try again.';
                exit();
            }
        }
        
        // check to see if name is set and not empty
        if(!isset($name) || empty($name)) {
            echo 'Error: Name cannot be empty. Please try again';
            exit();
        }
        
        if(!isset($size) || empty($size)) {
            echo 'Error: Size cannot be empty. Please try again';
            exit();
        }
        if(!is_numeric($size)) {
            $size = (int) $size;
            
            if(!is_numeric($size)) {
                echo 'Error: Size must be a number. Please try again.';
                exit();
            }
        }

        // Also check to make sure size is less than 30.
        if($size > 30 && $size < 0) {
            echo 'Error: Size must be greater than 0 and less than 30. Please try again.';
            exit();
        }
        
        if(!isset($coordinates) || empty($coordinates)) {
            echo 'Error: Coordinates cannot be empty. Please try again';
            exit();
        }
        
        // Right here if this was an app I was really going to use
        // I'd use explode() to grab the coordinates, using the "," as a delimeter
        // and cast both values as ints and make sure they didnt exceed $planetSize

        if(!isset($type)) {
            echo 'Error: Type cannot be empty. Please try again';
            exit();
        }
        
        // Check against array of types in terrain class.
        
        // Check to see if coordinates exist in database
        $sql = "SELECT id FROM terrain WHERE planet_id = '$planetID' AND 
                coordinate = '$coordinates'";

        $result = $mysqli->query($sql) or die(mysqli_error($mysqli));
        $num_rows = $result->num_rows;

        // If everything is ok update the database
        // Probably an easier way to do this with joins maybe?
        // Someone should let me know -- Lane
        $query = "UPDATE planets SET name = '$name', size = '$size' WHERE id = '$planetID'; ";
        // Two different querys based on how many rows
        if($num_rows == 0) {
            $query .= "INSERT INTO terrain VALUES ('', '$planetID', '$coordinates',
                    '$type')";
        } else {
            $query .= "UPDATE terrain SET coordinate = '$coordinates',
                    type = '$type' WHERE planet_id = '$planetID' AND coordinate = '$coordinates'";
        }

        $result = $mysqli->multi_query($query);
        
        header("Location: editPlanet.php?id=$planetID");
    }
    
    
    /**
     * 
     * @global object $mysqli
     * @return array
     */
    function getPlanets() {
        global $mysqli;
        
        $query = "SELECT * FROM planets";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $planets[] = $row;
        }
        
        return $planets;
    }
    
    /**
     * 
     * @global object $mysqli
     * @return int
     */
    function planetCount() {
        global $mysqli;
        
        $query = "SELECT id FROM planets";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        $count = $result->num_rows;
        
        return $count;
    }
    
    
    /**
     * Descripion: Deletes planet from db where planetid = id
     * 
     * @global object $mysqli
     * @param int $planetID
     */
    function deletePlanet($planetID) {
        global $mysqli;
        
        // Query to delete planet
        $query = "DELETE FROM planets WHERE id = '$planetID'";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        header("Location: listPlanets.php");
    }
}

?>
